<?php
/*----------------------------------------------------------------------
 * 视频播放管理：统计业务，与线下计费系统无关
 * Author: ming.nie
----------------------------------------------------------------------*/
namespace Common\Logic;
class BillingVideoPlayLogic
{
    /**
     * 版权系统：同步版权商的影片到版权影片库 ,貌似现在没有用了
     * @param  array
     * @return array
     */
    public function syncVideoPlay ($params)
    {
        $result = array ();
        $result_manager = array (
            0 => array ('status_code' => 0, 'status_message' => '数据更新失败'),
            1 => array ('status_code' => 1, 'status_message' => '数据更新成功'),
            3 => array ('status_code' => 3, 'status_message' => '参数错误'),
        );
        $status_code = 0;
        if (isset($params['host_name']) && !empty($params['host_name'])
            && isset($params['data_list']) && !empty($params['data_list'])
        ){
            $model = M('BillingVideoPlay');
            $copyrightVidelModel = M('CopyrightVideo');
            $current_time = time();
            $update_ids = array ();
            $status_code = 1;
            foreach ($params['data_list'] as $key => $value){
                $condition = array ();
                $condition['host_name'] = $params['host_name'];
                $condition['cinema_play_id'] = $value['id'];
                $check_rs = $model->where($condition)->find();
                if (!$check_rs){
                    $value['cinema_play_id'] = $value['id'];
                    unset($value['id']);
                    unset($value['is_sync']);
                    //获取当前的影片价格
                    $value['price'] = $copyrightVidelModel->where('video_id=' . $value['video_id'])->getField('price');
                    !$value['price'] && $value['price'] = 0;
                    $db_result = $model->data($value)->add();
                    if ($db_result){
                        $update_ids[] = $value['cinema_play_id'];
                    }
                }
            }
            if ($update_ids){
                $result['update_ids'] = $update_ids;
            }
        } else{
            $status_code = 3;
        }
        $result = array_merge($result, $result_manager[$status_code]);
        return $result;
    }

    /*
     * 对播放列表每条数据进行处理
     * return 数组
     * return msg 消息
     * return agent_id 代理商ID
     * return billing_video_play_type 2016计费方式
     * return billing_cloud_price 计费价格
     *
     */
    public function calculation ($find)
    {
        //获取内容
        $result['code'] = 1;
        $result['billing_cloud_price']=0;
        $result['billing_video_play_type']=0;
        $query = $this->checkIsLegal($find['host_name']);  //检测数据内容，并判断是直属影院还是代理商
        $cinema_id=$query['fid'];
        if ($query!==false){

            //生成结算表查询条件
            $where['start_time'] = array ('ELT', $find['create_time']);
            $where['end_time'] = array ('EGT', $find['create_time']);
            $where['host_name'] = $find['host_name'];
            $where['billing_video_play_type'] = array ('GT', 0);
            $where['agent_id'] = $query['agent_id'];
            $where['fid'] = $find['fid'] = $query['fid'];
            if ($query['agent_id'] > 0){
                unset($where['host_name']);
                unset($where['fid']);
            }else{
                unset($where['agent_id']);
                unset($where['fid']);
//                print_r($where);die;
            }
            $field = 'id,fid,agent_id,buy_hall_count,billing_video_play_type'; //结算表查询字段
            $billing = M('billing')->field($field)->where($where)->order('id DESC')->find(); //查询结算表结算规则
//            echo M('billing')->GetLastSql();
            $result['billing_video_play_type'] = $billing['billing_video_play_type'];
//            $result['order_sn']=M('cinema_order')->where(array('order_id'=>$find['order_id']))->getField('order_sn');
            $find['agent_id'] = $query['agent_id'];
            if (!empty($billing)){  //生成对于的结算数据，返回
                $billing['buy_hall_count'] == '' ? $find['buy_hall_count'] = 0 : $find['buy_hall_count'] = $billing['buy_hall_count'];
                $find['billing_video_play_type'] = $billing['billing_video_play_type'];
                $result['billing_cloud_price'] = $this->choseCount($find);
            }
        }
        return $result;
    }

    /**
     *检测代理商和直属影院，是否选择2016计费方式
     * @param $hostName
     * @return bool
    FunctionName：checkIsLegal
     */
    private function checkIsLegal ($hostName)
    {
        $result = M('cinema_host')->field('id as fid,billing_video_play_type,agent_id')
            ->where(array ('host_name' => $hostName))
            ->find();
//        echo M('cinema_host')->GetLastSql();
        if ($result['agent_id'] > 0){ //如果是代理商
            $result['billing_video_play_type'] = M('agent')
                ->where(array ('id' => $result['agent_id'], 'billing_video_play_type' => array ('GT', 0)))
                ->getField('billing_video_play_type');
//            unset($result['fid']);
        }
        if ($result['billing_video_play_type'] == ''){
            $result = false;
        }

        return $result;
    }

    /**
     *默认情况下几种扣费情况
     * @param $data
     * @return bool
    FunctionName：choseCount
     * author: DuanTao
     */
    private function choseCount ($data)
    {
        $price = 0;
        $cloud_price = $data['cloud_price'];
        if ($data['billing_video_play_type'] == 1 && $data['agent_id'] == 0){   //直属全年包断模式
            $price =0;
        }
        if ($data['billing_video_play_type'] == 2 && $data['agent_id'] == 0){  //直属平台单点模式2
            $price = $this->billingType2(1,$cloud_price);
        }
        if ($data['billing_video_play_type'] == 3 && $data['agent_id'] == 0){ //直属平台混合模式
            $price = $this->billingType2(1,$cloud_price);
        }
        if ($data['billing_video_play_type'] == 4 && $data['agent_id'] > 0){ //代理商包断摸索
            $price = 0;
        }
        if ($data['billing_video_play_type'] == 5 && $data['agent_id'] > 0){ //代理商单点模式
            $number = $data['buy_hall_count'];
            $priceOK = $this->billingType5($number,1,$cloud_price);
            $price = $priceOK['price'];
        }
        if ($data['billing_video_play_type'] == 6 && $data['agent_id'] > 0 && $data['is_new_video']==1){ //代理商模式混合
            $price = $this->billingType6(1,$cloud_price);
        }
        if ($data['billing_video_play_type'] == 7 && $data['agent_id'] > 0 && $data['is_new_video']==1){ //战略合作商
            $money = $this->billingType7(1,$cloud_price);
            $price = $money['times'];
        }
        return $price;
    }

    /**
     *按幕收费 5000/年/幕
     * @param $param幕个数
    FunctionName：billingType1
     * author: DuanTao
     */
    private function billingType1 ($param, $money = 5000)
    {
        return $param * $money;
    }

    /**
     *按次数10元/次
     * @param int $times
     * @param int $money
     * @return int
    FunctionName：billingType2
     * author: DuanTao
     */
    private function billingType2 ($times = 1, $money = 10)
    {
        return $times * $money;
    }

    /**
     *代理商收费方式按幕个数收费
     * @param $number幕数
     * @return int
    FunctionName：billingType3
     * author: DuanTao
     */
    private function billingType4 ($number)
    {
        $result = [];
        $price=round(5000/12,2); //获取平均每个月扣费金额，保留两位小数
        switch ($number){
            case $number <= 30:
                $result['totalPrice'] = $price * $number;  //小于30幕，无折扣，5000/幕/年
                $result['discount'] = '1';
                break;
            case $number > 30 && $number <= 50:
                $result['totalPrice'] = $price * 0.85 * $number;  //小于50幕，8.5折，5000*.085/幕/年
                $result['discount'] = '0.85';
                break;
            case  $number > 50 && $number <= 100:
                $result['totalPrice'] = $price * 0.8 * $number; //小于100幕，8折，5000*0.8/幕/年
                $result['discount'] = '0.8';
                break;
            case  $number > 100 && $number <= 200:
                $result['totalPrice'] = $price * 0.7 * $number; //小于200幕，7折，5000*0.7/幕/年
                $result['discount'] = '0.7';
                break;
            case  $number > 200:
                $result['totalPrice'] = $price * 0.6 * $number; //大于200幕，6折，5000*0.6/幕/年
                $result['discount'] = '0.6';
                break;
        }
        return $result;
    }

    /**
     *代理商收费方式按点击次数收费
     * @param $number
     * @param int $times
     * @return float|int
    FunctionName：billingType4
     * author: DuanTao
     */
    private function billingType5 ($number, $times = 1, $price=10)
    {
        $result = [];
        switch ($number){
            case $number <= 30:   //当幕数小于30的，时候，不打折
                $result['price'] = $price * $times;
                $result['discount'] = 1;
                break;
            case $number > 30 && $number <= 50: //当幕数在30与50之间的时候，对价格优惠0.85
                $result['price'] =$price * $times*0.85;
                $result['discount'] = 0.85;
                break;
            case $number > 50 && $number <= 100:  //当幕数在50与100之间的时候，对价格优惠0.8
                $result['price'] =$price * $times*0.8;
                $result['discount'] = 0.8;
                break;
            case $number > 100 && $number <= 200:  //当幕数在100与200之间的时候，对价格优惠0.7
                $result['price'] = $price * $times*0.7;
                $result['discount'] = 0.7;
                break;
            case $number > 200:  //当幕数在200以上的时候，对价格优惠0.6
                $result['price'] = $price* $times*0.6;
                $result['discount'] = 0.6;
                break;
        }
        return $result;
    }

    /**
     *代理商收费方式混合模式
     * @param $number幕数量
     * @param $time
     * @return int
    FunctionName：billingType6
     * author: DuanTao
     */
    private function billingType6 ($time = 1, $price)
    {
        return$price*$time;
    }

    /**
     *计算代理商混合模式每月固定扣费金额，并返回优惠比例
     * @param $number
     * @return array
    FunctionName：billingType6Money
     */
    private function billingType6Money ($number)
    {
        $result = [];
        $price=round( 3000 / 12,2);  //当面每月固定，扣费金额，保留两位小数
        switch ($number){
            case $number < 30:  //当幕数小于30的时候，没有优惠
                $result['totalPrice'] =  $price * 1;
                $result['discount'] = '1';
                break;
            case  $number > 30 && $number <= 50:  //当幕数在30与50之间，对就价格优惠0.85
                $result['totalPrice'] =$price*0.85;
                $result['discount'] = '0.85';
                break;
            case  $number > 50 && $number <= 100;  //当幕数在50与100之间的时候，对价格优惠0.8
                $result['totalPrice'] =$price*0.8;
                $result['discount'] = '0.8';
                break;
            case  $number > 100 && $number <= 200;  //当幕数在100与200之间的时候，对价格优惠0.7
                $result['totalPrice'] =$price*0.7;
                $result['discount'] = '0.7';
                break;
            case  $number > 200;  //当幕数在200以上的时候，对价格优惠0.6
                $result['totalPrice'] = $price*0.6;
                $result['discount'] = '0.6';
                break;
        }
        $result['totalPrice'] = $result['totalPrice'] * $number;
        return $result;
    }

    /**
     *代理商战略合作代理单次计费方式
     * @param $number幕数
     * @param $time点播次数
     * @param bool $tickle 是否返点策略
     * @return mixed
    FunctionName：billingType7
     * author: DuanTao
     */
    private function billingType7 ($time = 1,$price=10)
    {
        //每年计算一次
        $result['times'] = $time * $price;
        return $result;
    }

    /**
     *定时生成直属影院结算表数据
     * @param bool $all 用于强行补全所有结算数据
    FunctionName：checkBalanceCinema
     */
    public function checkBalanceCinema ($all = false)
    {
        $list = M('cinema_host')->field('id,host_name,join_time')
            ->where(array ('agent_id' => 0, 'join_time' => array ('EGT', strtotime('2015-1-1')), 'billing_video_play_type' => array ('BETWEEN', array (1, 3))))
            ->select();
//    echo M('cinema_host')->GetLastSql();die;
        foreach ($list as $rs){
            if ($all !== false){
                $this->makeBalance($rs['id']);
            } else{  //通过判断直属影院加入的那天的日期，判断与现在的日期天小于，如果小于。则生成一条数据
                $time = date("d H:i:s", $rs['join_time']);
                $getYear = date('Y-m-') . $time;
                $newTime = strtotime($getYear);
//        echo $newTime.'<br>';
                if ($newTime < time()){
                    $this->makeBalance($rs['id']);
                }
            }
        }
    }

    /**
     *定时生成代理商结算数据表
     * @param bool $all 用于强行补全所有结算数据
    FunctionName：checkBalanceAgent
     */
    public function checkBalanceAgent ($all = false)
    {
        $list = M('agent')->field('id,agent_time')
            ->where(array ('agent_time' => array ('EGT', strtotime('2015-1-1')), 'billing_video_play_type' => array ('GT', 0)))
            ->select();
        foreach ($list as $rs){
            if ($all !== false){
                $this->buildAgentBilling($rs['id']);
            } else{ //通过判断代理商加入的那天的日期，判断与现在的日期天小于，如果小于。则生成一条数据
                $time = date("d H:i:s", $rs['agent_time']);
                $getYear = date('Y-m-') . $time;
                $newTime = strtotime($getYear);
//        echo $newTime.'<br>';
                if ($newTime < time()){
                    $this->buildAgentBilling($rs['id']);
                }
            }
        }
    }

    /**
     *生成年返利数据
     * @param $array代理商数据
     * @return mixed
    FunctionName：buildAgentYearBilling
     */
    public function buildAgentYearBilling ($array)
    {
        $where['id'] = $array['id'];
       $data['start_time'] = strtotime($array['billing_year'] . '-01-01 00:00:00');
        $data['end_time'] = strtotime($array['billing_year'] . '-12-31 23:59:59');
        $data['type'] = 1;
        $data['discount'] = 1;
        $data['agent_id'] = $array['id'];
        $data['create_time'] = time();
        $data['join_time'] = $array['agent_time'];
        $data['billing_video_play_type'] = $array['billing_video_play_type'];
        $data['status'] = 1;
        $data['discount'] = 1;
        $data['buy_hall_count'] = $this->countAgentHall($array['id']);  //计算代理商所有幕数
        if ($data['buy_hall_count'] <= 300){  //计算返点比例
            $data['rebate'] = 0.15; //返点比例
        } elseif ($data['buy_hall_count'] > 300){
            $data['rebate'] = 0.2; //返点比例
        }

        $data['check_time'] = time();  //结算时间
        $sn_day = date('Ymd');
        $sn_count = substr(time(), 4, 10);
        $data['bill_sn'] = $sn_day . '0' . $sn_count;//结算流水号
        $video_play_money=M('copyright_order')
            ->where(array('agent_id'=>$array['id'],'video_play_is_clear'=>1,'create_time'=>array ('BETWEEN', array ($data['start_time'], $data['end_time']))))
            ->sum('billing_cloud_price');
        if(empty($video_play_money)){$video_play_money=0;}
        $data['money_total']=$data['money_really'] = $video_play_money; //实际结算金额
        $data['money_rebate'] = $video_play_money * $data['rebate']; //根据点播金额，返点金额数量
        $data['verifier'] = UID;
        $data['year'] = $array['billing_year'];
        return M('billing')->add($data);
    }

    /**
     *生成影院每月固定结算表
     * @param $fid
     * @return bool
    FunctionName：makeBalance
     */
    public function makeBalance ($fid)
    {
        $result = false;
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['billing_video_play_type'] = array ('BETWEEN', array (1, 3));
        $where['fid'] = $fid;
        $billing = M('billing')->where($where)->order('id DESC')->getField('id');
        if (!empty($billing)){ //检测结算表中是否有当月结算内容，如果有则直接返回数据内容
            $result = $billing;
        } else{   //搜索结算表中是否存在当月结算数据
            $join_data = M('billing')
                ->field('fid,join_time,billing_video_play_type,host_name,agent_id,cinema_name,end_time,billing_video_play_type,buy_hall_count,end_time')
                ->where(array ('fid' => $fid, 'billing_video_play_type' => array ('BETWEEN', array (1, 3))))
                ->order('id DESC')->find();
            if (!empty($join_data)){ //搜索结算表中是否有上个月的数据内容，如果有则读取上个月内容，然后读取主数据表中的幕数，及2016计费方式
                $join_data['buy_hall_count'] = $this->getCinemaHall($fid); //获取直属影院幕数量
                $makeTime = $this->makeTime($join_data['end_time']);  //获取当月开始和结束时间
                $join_data['start_time'] = $makeTime['firstMonth'];
                $join_data['end_time'] = $makeTime['lastMonth'];
                $join_data['billing_video_play_type'] = M('cinema_host')->where(array ('id' => $fid, 'billing_video_play_type' => array ('BETWEEN', array (1, 3))))->getField('billing_video_play_type'); //获取主表中的结算规则
                if ($join_data['buy_hall_count'] == ''){
                    $join_data['buy_hall_count'] = 0;
                }
                $billingPrice = $this->makeBillingPrice($join_data['billing_video_play_type'], $join_data['buy_hall_count']); //生成每月孤单扣费金额，及优惠比例
                $join_data['price'] = $billingPrice['totalPrice'];
                $join_data['discount'] = $billingPrice['discount'];
            } else{  //如果没有上个月的结束基础数据，就从主表中生成一个
                $join_data = M('cinema_host')
                    ->field('id as fid,join_time,billing_video_play_type,host_name,agent_id,cinema_name,buy_hall_count')
                    ->where(array ('id' => $fid, 'billing_video_play_type' => array ('BETWEEN', array (1, 3))))
                    ->find();
                if (empty($join_data)){ //主表中找不到数据的时候，中止操作
                    return false;
                }
                $makeTime = $this->makeTime($join_data['join_time']); //获取当月开始和结束时间
                $join_data['start_time'] = $makeTime['firstMonth'];
                $join_data['end_time'] = $makeTime['lastMonth'];
                if ($join_data['buy_hall_count'] == ''){
                    $join_data['buy_hall_count'] = 0;
                }
                $billingPrice = $this->makeBillingPrice($join_data['billing_video_play_type'], $join_data['buy_hall_count']); //生成每月孤单扣费金额，及优惠比例
                $join_data['price'] = $billingPrice['totalPrice'];
                $join_data['discount'] = $billingPrice['discount'];
            }
            if (!empty($join_data)){
                $join_data['create_time'] = time();
//        var_dump($join_data);die;
                $result = M('billing')->add($join_data);
            }
        }
        return $result;
    }

    /**
     *生成代理商结算表
     * @param $agentID代理商ID
     * @return bool
    FunctionName：buildAgentBilling
     */
    private function buildAgentBilling ($agentID)
    {
        $result = false;
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['agent_id'] = $agentID;
        $where['type'] = 0;
        $where['billing_video_play_type'] = array ('GT', 0);
        $billing = M('billing')->where($where)->order('id DESC')->getField('id');
        if (!empty($billing)){ //检测结算表中是否有当月结算内容，如果有则直接返回数据内容
            $result = $billing;
        } else{
            $join_data = M('billing')
                ->field('fid,join_time,billing_video_play_type,host_name,agent_id,cinema_name,end_time,buy_hall_count')
                ->where(array ('agent_id' => $agentID, 'type' => 0, 'billing_video_play_type' => array ('GT', 0)))
                ->order('id DESC')->find();
            if (!empty($join_data)){ //搜索结算表中是否有上个月的数据内容，如果有则读取上个月内容，然后读取主数据表中的幕数,和2016计费方式
                $join_data['buy_hall_count'] = $this->countAgentHall($join_data['agent_id']);  //获取中介幕数量
                $makeTime = $this->makeTime($join_data['end_time']);
                $join_data['start_time'] = $makeTime['firstMonth'];
                $join_data['end_time'] = $makeTime['lastMonth'];
                $join_data['billing_video_play_type'] = M('agent')->where(array ('id' => $agentID, 'billing_video_play_type' => array ('GT', 0)))->getField('billing_video_play_type'); //获取主表中的结算规则
                $join_data['buy_hall_count'] = $this->countAgentHall($join_data['agent_id']); //获取代理商幕数
                if ($join_data['buy_hall_count'] == ''){
                    $join_data['buy_hall_count'] = 0;
                }
                $billingPrice = $this->makeBillingPrice($join_data['billing_video_play_type'], $join_data['buy_hall_count']); //生成每月固定收费金额，和优惠比例
                $join_data['price'] = $billingPrice['totalPrice'];
                $join_data['discount'] = $billingPrice['discount'];
            } else{  //如果没有上个月的结束基础数据，就从主表中生成一个
                $join_data = M('agent')
                    ->field('id as agent_id,billing_video_play_type,agent_time as join_time')
                    ->where(array ('id' => $agentID, 'billing_video_play_type' => array ('GT', 0)))
                    ->find();
                if (empty($join_data)){  //见找不到数据的时候，终止后续操作
                    return false;
                }
                $makeTime = $this->makeTime($join_data['join_time']);
                $join_data['start_time'] = $makeTime['firstMonth'];
                $join_data['end_time'] = $makeTime['lastMonth'];
                $join_data['buy_hall_count'] = $this->countAgentHall($join_data['agent_id']); //获取代理商幕数
                if ($join_data['buy_hall_count'] == ''){
                    $join_data['buy_hall_count'] = 0;
                }
                $billingPrice = $this->makeBillingPrice($join_data['billing_video_play_type'], $join_data['buy_hall_count']); //生成每月孤单扣费金额，及优惠比例
                $join_data['price'] = $billingPrice['totalPrice'];
                $join_data['discount'] = $billingPrice['discount'];
            }
            if (!empty($join_data)){
                $join_data['create_time'] = time();
                if ($join_data['buy_hall_count'] == ''){
                    $join_data['buy_hall_count'] = 0;
                }
                $join_data['type'] = 0;
                $result = M('billing')->add($join_data);
            }
        }
        return $result;
    }

    /**
     *生成，开始和结束月份
     * @param $join_time
     * @return mixed
    FunctionName：makeTime
     * author: DuanTao
     */
    private function makeTime ($join_time)
    {
   /*     $day=date('d',$join_time);
        $day=(int)$day;
        $nowDay=date('d');
        $nowDay=(int)$nowDay;
        if($day<$nowDay){
            $firstMonth = date("Y-m-d", $join_time);
            $db['firstMonth'] = strtotime("$firstMonth -1 month");
            $db['lastMonth'] = strtotime($firstMonth) + 3600 * 24-1;
        }else{
            $firstMonth = date("Y-m-d", $join_time);
            $db['firstMonth'] = strtotime($firstMonth);
            $db['lastMonth'] =  strtotime("$firstMonth +1 month") + 3600 * 24-1;
        }*/
        $firstMonth = date("Y-m-d", $join_time);
        $db['lastMonth'] =  strtotime("$firstMonth +1 month");
        $db['firstMonth'] = strtotime($firstMonth)+1;
        return $db;
    }

    /**
     *获取中介幕的数量
     * @param $agentId
     * @return mixed
    FunctionName：countAgentHall
     * author: DuanTao
     */
    private function countAgentHall ($agentId)
    {
        $result = M('cinema_host')->where(array ('agent_id' => $agentId))->SUM('buy_hall_count');
        if (empty($result)){
            $result = 0;
        }
        return $result;
    }

    /**
     *获取直属影音幕数量
     * @param $fid
     * @return int
    FunctionName：getCinemaHall
     */
    private function getCinemaHall ($fid)
    {
        $count = M('cinema_host')->where(array ('id' => $fid))->getField('buy_hall_count');
        if (empty($count)){
            $count = 0;
        }
        return $count;
    }

    /**
     *主要用于前台展示，显示当月结算在哪天
     * @param $time @数据库billing表中的end_time
     * @return mixed
    FunctionName：makeBillingTime
     */
    public function makeBillingTime ($time)
    {
        $day = date("d", $time );
        return $day;
    }

    /**
     *获取直属影院列表
     * @param $get
     * @return mixed
    FunctionName：getCinemaList
     */
    public function getCinemaList ($get)
    {
        //生成查询条件
        $where['join_time'] = array ('GT', 0);
        $where['billing_video_play_type'] = array ('GT', 0);
        $where['agent_id'] = 0;
        if (!empty($get['status'])){ //搜索计费类型
            $where['billing_video_play_type'] = $get['status'];
        }
        //搜索结算时间
        if ($get['start_time'] && $get['end_time']){
            $where['join_time'] = array (array ('EGT', strtotime($get['start_time'])), array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1));
        } elseif ($get['start_time']){
            $where['join_time'] = array ('EGT', strtotime($get['start_time']));
        } elseif ($get['end_time']){
            $where['join_time'] = array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1);
        }

        //搜索关键字
        if (!empty($get['keywords'])){
            $map['host_name'] = array ('LIKE', '%' . $get['keywords'] . '%');
            $map['cinema_name'] = array ('LIKE', '%' . $get['keywords'] . '%');
            $map['_logic'] = 'OR';
            $where['_complex'] = $map;
        }
        $model = M('cinema_host');
        $count = $model->where($where)->count();
        $Page = new \Think\Page2($count, 14);
        $result['page'] = $Page->show();
        $result['list'] = $model->where($where)
            ->field('id,host_name,cinema_name,join_time,billing_video_play_type,buy_hall_count,type')
            ->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        if (!empty($result['list'])){
            $result['money_really_total'] = 0;
            $BillingType = C('CINEMA_BILLING_VIDEO_PLAY_TYPE');
            foreach ($result['list'] as $key => $rs){
                $result['list'][$key]['billing_time'] = $this->makeBillingTime($rs['join_time']);//生成结算时间
                $result['list'][$key]['billing_video_play_type'] = $BillingType[$rs['billing_video_play_type']];  //获取计费类型
                $result['money_really_total'] = $result['money_really_total'] + $rs['money_really'];
            }
        }
        return $result;
    }

    /**
     * 获取代理商列表
     * @param $get
     * @return mixed
    FunctionName：getAgentList
     */
    public function getAgentList ($get)
    {

        //生成搜索条件
        $map['billing_video_play_type'] = array ('GT', 0);
        if(!empty($get['videoPlayType'])){
            $map['billing_video_play_type']=$get['videoPlayType'];
        }

        if ($get['start_time'] && $get['end_time']){
            $map['agent_time'] = array (array ('EGT', strtotime($get['start_time'])), array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1));
        } elseif ($get['start_time']){
            $map['agent_time'] = array ('EGT', strtotime($get['start_time']));
        } elseif ($get['end_time']){
            $map['agent_time'] = array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1);
        }

        //代理商名称
        $keywords = I('get.keywords', '', 'trim');
        if (!empty($keywords)){
            $where['agent_name'] = array ('LIKE', '%' . $keywords . '%');
            $where['agentid'] = array ('LIKE', '%' . $keywords . '%');
            $where['_logic']='OR';
            $map['_complex']=$where;
        }
        $count = D('agent')->where($map)->count();
        $Page = new \Think\Page2($count, 14);
        $result['page'] = $Page->show();
        $list = D('agent')->where($map)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        //查询代理商影院数据量
        $videoPlayType=C('AGENT_BILLING_VIDEO_PLAY_TYPE');
        foreach ($list as $key => $rs){
            $cinema = M('cinema_host')
                ->field('sum(`buy_hall_count`) as hall,count(`id`) as cinema_count')
                ->where(array ('agent_id' => $rs['id']))
                ->find();
            $list[$key]['cinema_host_hall'] = $cinema['cinema_count'];
            $list[$key]['hall'] = $cinema['hall'];
            $list[$key]['billing_video_play_type'] = $videoPlayType[$rs['billing_video_play_type']];
            $list[$key]['end_day'] = $this->makeBillingTime($rs['agent_time']);
        }
        $result['list'] = $list;
        return $result;
    }

    /**
     *获取直属影院结算列表
     * @param $fid @直属影院ID
     * @return mixed
    FunctionName：getCinemaBalance
     */
    public function getCinemaBalance ($fid)
    {
        $this->forCinemaBalance($fid); //检测直属影院结算表是否完善，自动补全数据
        $get = I('get.', '', 'trim');

        //生成查询条件
        if (!empty($get['start_time']) && !empty($get['end_time'])){
            $where['end_time'] = array ('BETWEEN', array(strtotime($get['start_time'],strtotime($get['end_time']) + 3600 * 24 - 1)));
        }
        if (!empty($get['start_time'])){
            $where['end_time'] = array ('EGT', strtotime($get['start_time']));
        }
        if (!empty($get['end_time'])){
            $where['end_time'] = array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1);
        }
        $where['fid'] = $fid;
        $where['agent_id'] = 0;
        $where['status'] = array ('IN', array (1, 2));  //不显示未处理的结算表
        $model = M('billing');
        $count = $model->where($where)->count();
        $Page = new \Think\Page2($count, 15);
        $result['page'] = $Page->show();// 分页显示输出
        $result['list'] = $model->where($where)
            ->field('id,fid,end_time,money_total,money_really,payfor_type,verifier,status,cinema_name,bill_sn')
            ->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $result['money_really_total'] = $model->where($where)->sum('money_really');
        if (!empty($result['list'])){
            $payForType = C('PAY_FOR_TYPE');
            foreach ($result['list'] as $key => $rs){
                $result['list'][$key]['payfor_type'] = $payForType[$rs['payfor_type']]; //获取支付方式
                $result['list'][$key]['statusWord'] = $this->getBillingStatus($rs['status']);
                $result['list'][$key]['verifier'] = $this->getCheckBillingName($rs['verifier']);
            }
        }
//    echo $model->GetLastSql();
        return $result;
    }

    /*
     * 获取影院结算的时候，先检测数据内容是否完整，不然生成结算表，知道今天为止
     */
    protected function forCinemaBalance ($fid)
    {
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['fid'] = $fid;
        $where['type']=0;
        $where['billing_video_play_type'] = array ('GT', 0);
        $billing = M('billing')->where($where)->order('id DESC')->getField('id');
        if (empty($billing)){
            $result = $this->makeBalance($fid);
            if ($result !== false){
                $this->forCinemaBalance($fid);
            }
        } else{
            return true;
        }
    }

    /**
     *获取代理商结算表
     * @param $id
     * @param int $limit
     * @return mixed
    FunctionName：getAgentBalance
     */
    public function getAgentBalance ($id,$limit=15)
    {
        $this->forAgentBalance($id);  //效验代理商结算表是否完善，否则自动补全

        //生成查询条件
        $where['agent_id'] = $id;
        $where['type'] = 0;
        $get = I('request.', '', 'trim');
        $where['end_time'] = array ('ELT', time());
        if(!empty($get['start_time']) && !empty($get['end_time']))
            $where['end_time']=array('BETWEEN',array(strtotime($get['start_time'],strtotime($get['end_time']) + 3600 * 24 - 1)));
        if (!empty($get['start_time'])){
            $where['end_time'] = array ('EGT', strtotime($get['start_time']));
        }
        if (!empty($get['end_time'])){
            $where['end_time'] = array ('ELT', strtotime($get['end_time']) + 3600 * 24 - 1);
        }
        //代理商名称
        $keywords = I('get.keywords', '', 'trim');
        if (!empty($keywords)){
            $map['agent_name'] = array ('LIKE', '%' . $keywords . '%');
        }
        $where['status'] = array ('IN', array (1, 2)); //只显示状态为未处理和已处理的结算表
        $model = M('billing');
        $count = $model->where(array ($where))->count();
        $Page = new \Think\Page2($count, $limit);
        $result['page'] = $Page->show();// 分页显示输出
        $result['page_count']=$count;
        $result['list'] = $model->where($where)
            ->field('id,fid,discount,end_time,money_total,money_really,payfor_type,verifier,status,cinema_name,buy_hall_count,bill_sn')
            ->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $result['money_really_total'] = $model->where($where)->sum('money_really');
        if (!empty($result['list'])){
            $payForType = C('PAY_FOR_TYPE');
            foreach ($result['list'] as $key => $rs){
                $result['list'][$key]['payfor_type'] = $payForType[$rs['payfor_type']];  //获取结算方式
                $result['list'][$key]['statusWord'] = $this->getBillingStatus($rs['status']);  //获取结算状态
                $result['list'][$key]['verifier'] = $this->getCheckBillingName($rs['verifier']);  //获取结算审核人
            }
        }
        return $result;
    }

    /*
     * 检测代理商是否存在有效结算单
     */
    private function forAgentBalance ($id)
    {
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['agent_id'] = $id;
        $where['type'] = 0;
        $billing = M('billing')->where($where)->order('id DESC')->getField('id');
        if (empty($billing)){
            $result = $this->buildAgentBilling($id);
            if ($result !== false){
                $this->forAgentBalance($id);
            }
        } else{
            return true;
        }
    }

    /*
     * 获取影院消费列表
     */
    public function getVideoPlayList ($inf, $limit = 15)
    {

        $result = [];
        $model = M('copyright_order');
        if (I('get.hostName') != ''){
            $where['a.host_name'] = I('get.hostName');
        }

        //针对代理商计费混合模式战略合作代理
        if($inf['billing_video_play_type']>5){
            $where['a.is_new_video']=$map['is_new_video']=1;
        }
        $map['create_time'] = $where['a.create_time'] = array ('BETWEEN', array ($inf['start_time'], $inf['end_time']));
        $map['billing_video_play_type'] = $where['a.billing_video_play_type'] = array ('GT', 0);
        $map['host_name'] = $where['a.host_name'] = $inf['host_name'];
        $map['video_play_is_clear'] = $where['a.video_play_is_clear'] = 1;
        if ($inf['agent_id'] > 0){
            $map['agent_id'] = $where['a.agent_id'] = $inf['agent_id'];
            unset($where['a.host_name']);
            unset($map['host_name']);
        }
        $join = 'LEFT JOIN mt_cinema_host c ON c.host_name=a.host_name';
        $select = $model->field('SUM(`billing_cloud_price`) as total_price,COUNT(`id`) as total_count')->where($map)->find();
        $result['cinemaType'] = $model->alias('a')->field('c.cinema_name')->where($where)->join($join)->group('c.cinema_name')->select();

        $result['totalPrice'] = $select['total_price'];
        $result['page_count']=$select['total_count'];
        if(empty($result['totalPrice'] )){$result['totalPrice'] =0;}
        $Page = new \Think\Page2($select['total_count'], $limit);
        $result['page'] = $Page->show();
        $result['list'] = $model->alias('a')
            ->field('a.order_sn,a.is_new_video,a.create_time,a.billing_cloud_price,a.video_name,c.cinema_name,a.play_time')
            ->where($where)->group('a.id')->order('a.create_time desc')->join($join)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($result['list'] as $key=>$rs){
            $result['list'][$key]['play_time']=$this->makePlayTime($rs['play_time']);
        }
        return $result;
    }

    /**
     *格式化播放时间，转换成人能看懂的格式
     * @param $data
     * @return string
    FunctionName：makePlayTime
     */
    private function makePlayTime($data){
        $time='';
        $data=$data/1000; //去除毫秒
        $hour=floor ($data/3600);
        $minute=floor (($data-$hour*3600)/60);
        $second=$data%60;
        if($hour>0){
            $time.=$hour.'小时';
        }
        if($minute>0){
            $time.=$minute.'分钟';
        }
        if($second>0){
            $time.=$second.'秒';
        }
        return $time;
    }

    /*
     * 保存直属影院结算审核
     */
    public function SaveCinemaAudit ($post)
    {
        $post['verifier'] = UID;
        $post['status'] = 2;
        $post['check_time'] = time();
        $result = M('billing')->save($post);
        if ($result !== false){
            return true;
        } else{
            return false;
        }
    }

    /*
     * 保存中介结算审核
     */
    public function SaveAgentAudit ($post, $checkYear = false)
    {
        $post['verifier'] = UID;
        $post['status'] = 2;
        $post['check_time'] = time();
        $result = M('billing')->save($post);
        if ($result !== false){
            return true;
        } else{
            return false;
        }
    }

    /*
     * 获取结算处理状态
     */
    public function getBillingStatus ($type)
    {
        $arr = [
            '0' => '系统未处理',
            '1' => '<span style="color: red">未结算</span>',
            '2' => '已结算'
        ];
        return $arr[$type];
    }

    /*
     * 获取结算表审核人姓名
     */
    public function getCheckBillingName ($uid)
    {
        return M('user')->where(array ('user_id' => $uid))->getField('user_name');
    }

    /**
     *显示未结算明细
     * @return mixed
    FunctionName：showNoBalance
     */
    public function showNoBalance ()
    {
        $fid = I('get.fid');
        $agentID = I('get.agentID');
        if (!empty($fid)){ //当检测到是直属影院
            $where['fid'] = $fid;
        } elseif (!empty($agentID)){  //当检测到是代理商
            $where['agent_id'] = $agentID;
            unset($where['fid']);
        }
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['status'] = 0;
        $find = M('billing')->field('*')->where($where)->find();
        if (empty($find)){
            $find['code'] = 0; //未找到结算单
            return $find;
        }
        if ($find['billing_video_play_type'] == 0){
            $find['code'] = 1; //结算摸索为空
            return $find;
        }
        $billingType = (C('CINEMA_BILLING_VIDEO_PLAY_TYPE') + C('AGENT_BILLING_VIDEO_PLAY_TYPE'));
        $find['billing_video_play_type_word'] = $billingType[$find['billing_video_play_type']];
        $result = $this->getVideoPlayList($find, 15);
        $find['video_play_list'] = $result['list'];
        $find['cinemaType'] = $result['cinemaType'];
        $find['page'] = $result['page'];
        $find['video_play_price_total']=$result['totalPrice'];
        $find['video_play_price_total'] = $result['totalPrice'];
        if (!empty($agentID)){
            $find['agent_name'] = M('agent')->where(array ('id' => $agentID))->getField('agent_name');
        }
        $find['formula']=$this->makeFormulaPrice($find);
        if(!empty($fid)){
            $find['cinema_name']=$this->selectCinemaName($fid);
        }
        return $find;
    }

    /**
     *通过计费方式和幕数，算出，每月固定扣费金额
     * @param $billingType
     * @param $videoHall
     * @return array
    FunctionName：makeBillingPrice
     */
    private function makeBillingPrice ($billingType, $videoHall)
    {
        $result = [];
        if (empty($videoHall)){
            $result['totalPrice'] = 0;
            $result['discount'] = '1';
        } else{
            switch ($billingType){
                case 1:
                    $totalPrice = $this->billingType1($videoHall);
                    $result['totalPrice'] = $totalPrice / 12;
                    $result['discount'] = '1';
                    break;
                case 2:
                    $result['totalPrice'] = 0;
                    $result['discount'] = '1';
                    break;
                case 3:
                    $result['totalPrice'] = $videoHall * round(3000 / 12,2);
                    $result['discount'] = '1';
                    break;
                case 4:
                    $result = $this->billingType4($videoHall);
                    break;
                case 5:
                    $result = $this->billingType5($videoHall);
                    break;
                case 6:
                    $result = $this->billingType6Money($videoHall);
                    break;
                case 7:
                    $result['totalPrice'] =  round(1000/ 12,2)*$videoHall;
                    $result['discount'] = '1';
            }
        }

        return $result;
    }

    /*
     * 结算表整理完成，更改状态0为1后台可见
     */
    public function checkBillingAll ($limit = 10,$check=false)
    {
        if($check===false){
            $where['end_time'] = array ('ELT', time());
        }
        $where['status'] = 0;
        $where['billing_video_play_type'] = array ('GT', 0);
        $list = M('billing')->field('')->where($where)->limit($limit)->order('id ASC')->select();  //查找数据，最多一次处理10条
        if (!empty($list)){
            foreach ($list as $rs){
                $this->updateBilling($rs);
            }
        }
    }

    /*
     * 结算并更新结算表
     */
    private function updateBilling ($data)
    {
        $db['id'] = $data['id'];

        //对数据进行效验，检查前播放记录表中的所有数据是否都已经是处理过的
        $where['create_time']=array ('BETWEEN',array ($data['start_time'], $data['end_time']));
        $where['video_play_is_clear']=0;
        $find=M('copyright_order')->field('id')->where($where)->find();
        if(!empty($find)){
            return false;
        }

        $result = $this->getVideoPlayList($data);
        $db['money_total'] = $data['price'] + $result['totalPrice']; //结算总金额
        $db['status'] = 1;
        $db['billing_video_play_type'] = $data['billing_video_play_type'];
        $db['update_time'] = time();
        $sn_day = date('Ymd');
        $sn_count = substr(time(), 4, 10);
        $db['bill_sn'] = $sn_day . '0' . $sn_count;//结算流水号
        return M('billing')->save($db);
    }

    /**
     *代理商年结算列表
     * @param int $limit
     * @return mixed
    FunctionName：billingYearCheck
     */
    public function billingYearCheck ($limit = 10)
    {

        //生成搜索条件
        $get = I('get.', '', 'trim');
        $where['a.year'] = array ('ELT', date('Y'));
        $where['a.type'] = 1;
        $where['a.status'] = array ('GT', 0);
        if (!empty($get['agentName'])){
            $map['b.agent_name'] = array ('LIKE', '%' . $get['agentName'] . '%');
            $map['b.agentid'] = array ('LIKE', '%' . $get['agentName'] . '%');
            $map['_logic'] = 'OR';
            $where['_complex'] = $map;
        }
        if (!empty($get['year'])){
            $where['a.year'] = $get['year'];
        }
        //查询数据
        $model = M('billing');
        $join = 'JOIN mt_agent b ON a.agent_id=b.id';
        $total_count = $model->alias('a')->join($join)->where($where)->count();
        $Page = new \Think\Page2($total_count, $limit);
        $result['page'] = $Page->show();
        $result['list'] = $model->alias('a')->join($join)
            ->field('a.id,a.bill_sn,a.check_time,a.money_really,a.buy_hall_count,a.rebate,a.money_rebate,status,b.agentid,b.agent_name')
            ->where($where)->order('id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($result['list'] as $key => $rs){
            $result['list'][$key]['statusWord'] = $this->getBillingStatus($rs['status']);  //获取结算状态，转换成中文描述
        }
        return $result;
    }

    /**
     *获取有代理商返点记录的年份
     * @return mixed
    FunctionName：haveBillingYearType
     */
    public function haveBillingYearType ()
    {
        return M('billing')->field('year')->where(array ('type' => 1, 'status' => array ('GT', 0)))->group('year')->select();
    }

    /**
     *生成年终结算内容,初始开始年份为2015，代理商加入时间也是2015年初
     * @param int $limit
     * @param bool $check 用户测试的时候强行结算当年数据使用
    FunctionName：yearBillingBalance
     */
    public function yearBillingBalance ($limit = 10,$check=false)
    {
        $this->checkAgentYear(); //效验结算的内容是否合法
        if($check!==true){
            $where['billing_year'] = array('BETWEEN',array(2015,(date('Y') - 1)));
            $map['status'] = array ('LT', 2);
        }else{
            $where['billing_year'] = date('Y');
        }
        $where['agent_time'] = array ('EGT', strtotime('2015-1-1'));
        $where['billing_video_play_type'] = 7;
        $list = M('agent')->field('id,agent_time,agent_time,billing_video_play_type,billing_year')->where($where)->limit($limit)->select();
        foreach ($list as $rs){
            //查询结算表内容是否全部都审核通过了
            $map['agent_id'] = $rs['id'];
            $map['type'] = 0;
            $map['end_time'] = array ('BETWEEN', array (strtotime($rs['billing_year'] . '-01-01 00:00:00'), strtotime($rs['billing_year'] . '-12-31 23:59:59')));
            $count = M('billing')->where($map)->count();

            if ($count==0){  //如果都结算了，生成一条年结算数据
                $result = $this->buildAgentYearBilling($rs);
                if ($result !== false){
                    M('agent')->where(array ('id' => $rs['id']))->save(array ('billing_year' =>  $rs['billing_year']+1));
                }
            }
            if($check===true){
                $result = $this->buildAgentYearBilling($rs);
                if ($result !== false){
                    M('agent')->where(array ('id' => $rs['id']))->save(array ('billing_year' =>  $rs['billing_year']+1));
                }
            }
        }
    }

    /**
     *效验代理商是否是战略合作代理，及年返点记录初始状态是否正确
     * 如果战略代理商的billing_year为0，则获取代理商加盟的年份为初始年份
     * @param int $limit
    FunctionName：checkAgentYear
     */
    private function checkAgentYear($limit=10){
        $where['billing_video_play_type'] = 7;
        $where['billing_year']=0;
        $list = M('agent')->field('id,agent_time')->where($where)->limit($limit)->select();
        foreach($list as $rs){
            $rs['billing_year']=date('Y',$rs['agent_time']);
            M('agent')->save($rs);
        }
    }

    //平台计费系统数据更新
    public function clearVideoPlayData ()
    {
        echo '<pre>';
        $model = M();
        $videoModel = M('Video');
        $mt_copyright_order = M('CopyrightOrder');
        $sql = 'SELECT * FROM mt_copyright_order WHERE video_play_is_clear = 0 limit 60';
        $rs = $model->query($sql);
        $billingVideoPlayLogic = new \Common\Logic\BillingVideoPlayLogic();
        //遍历数据记录，更新数据值
        foreach ($rs as $key => $value){
            //计费逻辑参数
            $calculation_params = $value;
            //查询影片信息
            $video = $videoModel->where('id=' . $value['video_id'])->find();

            //是否是新片儿
//            if ($video['new_film_start'] <= $value['create_time'] && $video['new_film_end'] >= $value['create_time']){
//                $calculation_params['is_new_video'] = 1;
//            } else{
//                $calculation_params['is_new_video'] = 0;
//            }

            //通过接口获取影片价格，影院ID，播放时间；
            unset($i_params);
            unset($params);
            $url = C('COPYRIGHT_HOST') . '/Home/Interface';
            echo $url . "\n";
            echo date('Y-m-d H:i:s') . "\n";
            $post_data = array ();
            //调用模块
            $post_data['class'] = 'Finance';
            $post_data['method'] = 'GetVideoPrice';
            //查询参数
            $i_params['video_id'] = $value['video_id'];
            $i_params['cinema_id']=M('cinema_host')->where(array('host_name'=>$value['host_name']))->getField('id'); //获取影院ID
//            $i_params['cinema_name']=$value['host_name'];
            $i_params['day'] = $value['create_time'];
            //组合成参数
            $i_params = json_encode($i_params);
            $post_data['params'] = $i_params;
            $params['post_data'] = $post_data;
            $params['method'] = 'post';
            //发送请求，获取结果
            $res = getNetContents($url, $params);
            $result = json_decode($res, true);
            dump($params);
            dump($result);
            //判断版权商ID是否存在，如果存在，则说明这个影片是版权商系统的，则价格为新片价格，
            $video['price']=0;
            if (!empty($result['result']['data']['copyright_user_id'])){
                $video['price'] = $result['result']['data']['price']; //影片价格
                $calculation_params['is_new_video'] = 1; //新片
            } else{
                $calculation_params['is_new_video'] = 0; //老片
            }

            $calculation_params['cloud_price']=$video['price'];

            echo '<br>';
            //计费逻辑处理
            $calculation_rs = $billingVideoPlayLogic->calculation($calculation_params);
            print_r($calculation_rs);
            echo '<br>==========================<br/>';
            //处理成功，更新数据记录要素
            if (1 == $calculation_rs['code']){
                $update_data = array ();
                $update_data['video_name']=$result['result']['data']['video_name'];
                $update_data['video_play_is_clear'] = 1;
//                $update_data['order_sn'] = $calculation_rs['order_sn'];
                $update_data['cloud_price'] = $video['price'];
                $update_data['billing_cloud_price'] = $calculation_rs['billing_cloud_price'];
                $update_data['is_new_video'] = $calculation_params['is_new_video'];
                $update_data['billing_video_play_type'] = $calculation_rs['billing_video_play_type'];
                if(empty($update_data['billing_video_play_type'])){
                    $update_data['billing_video_play_type']=0;
                }
                    //获取影院代理商级别
                    $agentInf=M('cinema_host')->field('agent_level_1,agent_level_2,id,agent_id')->where(array('host_name'=>$value['host_name']))->find();
                    $update_data['agent_level_1'] = $agentInf['agent_level_1'];
                    $update_data['agent_level_2'] = $agentInf['agent_level_2'];
                    $update_data['cinema_id'] = $agentInf['id'];
                    $update_data['agent_id'] = $agentInf['agent_id'];

                $mt_copyright_order->data($update_data)->where('id=' . $value['id'])->save();
            }
        }
    }

    /*
     * 生成计费方式公式
     */
    public function makeFormulaPrice($inf){

        switch ($inf['billing_video_play_type']){
            case 1:
                $formula=$this->formatNumber($inf['price']).'= '.$this->formatNumber($inf['price']/$inf['buy_hall_count']).'(元/幕/月 ) * '.$inf['buy_hall_count'].'(影院目数) ';
                break;
            case 2:
                $formula=$this->formatNumber($inf['video_play_price_total']).' (当月点播总价格)';
                break;
            case  3:
                $formula=$this->formatNumber($inf['price']+$inf['video_play_price_total']).' = '.
                    $this->formatNumber($inf['price']/$inf['buy_hall_count']).'(元/幕/月 ) * '.$inf['buy_hall_count'].'(影院目数) + '.$this->formatNumber($inf['video_play_price_total']).' (当月点播总价格)';
                break;
            case 4:
                $formula=$this->formatNumber($inf['price']+$inf['video_play_price_total']).' = '.
                    $this->formatNumber($inf['price']/$inf['buy_hall_count']/$inf['discount']).'(元/幕/月 ) * '.$inf['buy_hall_count'].'(影院目数) * '. ($inf['discount']*100).'% (折扣率)';
                break;
            case 5:
                $formula=$this->formatNumber($inf['video_play_price_total']).' = '.
                    $this->formatNumber($inf['video_play_price_total']/$inf['discount']).' (当月点播总价格) *  '.($inf['discount']*100).'% (折扣率)';
                break;
            case 6:
                $formula=$this->formatNumber($inf['price']+$inf['video_play_price_total']).' = '.
                    $this->formatNumber($inf['price']/$inf['buy_hall_count']/$inf['discount']).'(元/幕/月 ) * '.$inf['buy_hall_count'].'(影院目数) * '.($inf['discount']*100).'% (折扣率) + '.
                    $this->formatNumber($inf['video_play_price_total']).'(当月点播总价格)';
                break;
            case 7:
                $formula=$this->formatNumber($inf['price']+$inf['video_play_price_total']).' = '.
                    $this->formatNumber($inf['price']/$inf['buy_hall_count']/$inf['discount']).'(元/幕/月 ) * '.$inf['buy_hall_count'].'(影院目数) + '.
                    $this->formatNumber($inf['video_play_price_total']).' (当月点播总价格)';
                break;
        }
        return $formula;
    }

    /**
     *格式化数字
     * @param $number
     * @return int
    FunctionName：formatNumber
     */
    private static  function formatNumber($number){
        return number_format(round($number,2),2,'.','');
    }

    /*
     *代理商结算列表，用于提供接口
     */
    public function agentBalance ($params){
        if(empty( $params['agent_id'])){
            return  null;
        }
        $result = $this->getAgentBalance($params['agent_id'],$params['limit']); //获取代理商结算表
        unset($result['page']);
        $result['data_count']=$result['page_count'];
        return $result;
    }

    /*
     * 代理商未结算内容，用于提供接口
     */
    public function  agentNoBalance($params){
        $agentID =(int)$params['agent_id'];
        $where['start_time'] = array ('ELT', time());
        $where['end_time'] = array ('EGT', time());
        $where['status'] = 0;
        $where['agent_id']=$agentID;
        $find = M('billing')->field('*')->where($where)->find();
        if (empty($find)){
            $find['code'] = 0; //未找到结算单
            return $find;
        }
        if ($find['billing_video_play_type'] == 0){
            $find['code'] = 1; //结算模式为空
            return $find;
        }
        if($params['limit']==''){
            $params['limit']=15;
        }
        $billingType = (C('CINEMA_BILLING_VIDEO_PLAY_TYPE') + C('AGENT_BILLING_VIDEO_PLAY_TYPE'));
        $find['billing_video_play_type_word'] = $billingType[$find['billing_video_play_type']];
        $result = $this->getVideoPlayList($find, $params['limit']);
        $find['page_count']=$result['page_count'];
        $find['video_play_list'] = $result['list'];
        $find['cinemaType'] = $result['cinemaType'];
        if (empty($result['totalPrice'])){
            $result['totalPrice'] = 0;
        }
        $find['video_play_price_total'] = $result['totalPrice'];
        $query = M('agent')->field('billing_video_play_type,agent_name')->where(array ('id' => $agentID))->find();
        $find['agent_name'] = $query['agent_name'];
        $find['formula'] = $this->makeFormulaPrice($find);
        if ($query['billing_video_play_type'] < 4 ){
            $db = [];
            foreach ($find as $key => $rs){
                $db[$key] = '';
            }
            $find = $db;
        }
        return $find;
    }

    /**
     * 代理商结算表详情，用于提供接口
     * @param $params
     * @return array|null
    FunctionName：agentBalanceDetails
     */
    public function agentBalanceDetails($params){
        $inf = M('billing')->field('*')->where(array ('id' => $params['dataID']))->find();
        if(empty($inf)){
            return null;
        }
        $result = $this->getVideoPlayList($inf,$params['limit']);  //获取播放记录
        unset($result['page']);
        $inf['status'] = $this->getBillingStatus($inf['status']); //获取审核状态
        $inf['agent_name'] = M('agent')->where(array ('id' => $inf['agent_id']))->getField('agent_name');         //获取代理商名称
        $inf['verifier'] = $this->getCheckBillingName($inf['verifier']);  //获取审核人名称
        $inf['videoTotalPrice']=$result['totalPrice'];
        $inf['cinemaType']= $result['cinemaType']; //影院名称列表
        $agentBillingType = C('AGENT_BILLING_VIDEO_PLAY_TYPE');
        $inf['billingType'] = $agentBillingType[$inf['billing_video_play_type']]; //获取结算方式
        $inf['formula']=$this->makeFormulaPrice($inf);
        $result['inf']=$inf;
        return $result;
    }

    /**
     * explain:获取影院名称
     * @param $CinemaID
     * @return string
     * author:DuanTao
     */
     public function selectCinemaName($CinemaID){
        $find=M('cinema_host')->field('type,cinema_name')->find($CinemaID);
        switch ($find['type']){
            case 4;
                $cinema_name='小帅';
                break;
            case 8:
                $cinema_name='携旅';
                break;
            case 9:
                $cinema_name='耀莱';
                break;
            case 10;
                $cinema_name='迈智威';
                break;
            case 11;
                $cinema_name='1905';
                break;
            default:
                $cinema_name=$find['cinema_name'];
                if(empty($cinema_name)){
                    $cinema_name='--';
                }
        }
        return $cinema_name;
    }
}